<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\AliSMS;
use app\admin\model\ChangeModel;
use app\admin\model\ArchivesDeceasedModel;
use app\admin\model\CarveModel;
use app\admin\model\ContractModel;
use app\admin\model\MaintenanceProjectModel;
use app\admin\model\OrderDepositModel;
use app\admin\model\OrderDepositSendModel;
use app\admin\model\OrderModel;
use app\admin\model\OrderPayLogModel;
use app\admin\model\ProductInfoModel;
use app\admin\model\ProtectPaymentModel;
use app\admin\model\RetreatTombModel;
use app\admin\model\ServiceBuriedModel;
use app\admin\model\ServiceDepositModel;
use app\admin\model\ServiceWeibaoModel;
use cmf\controller\AdminBaseController;
use think\Db;
use app\admin\model\AdminMenuModel;
use think\Validate;

class AftersaleController extends AdminBaseController
{

    protected $customerId =0;
    protected $tombId =0;
    protected $tomb_type =0;
    protected $tomb_num =0;
    protected $result_list =0;
    protected $dep_list =[];
    protected $users_array =[];
    protected $tomb_typei =0;//0购买；1寄存

    public function initialize()
    {
        parent::initialize();
//        session('aftersale.customer_id', 0);
        $this->customerId = session('aftersale.customer_id');
        $this->tombId = session('aftersale.tomb_id');
        $this->tomb_type = session('aftersale.tomb_type');
        $this->tomb_typei = session('aftersale.tomb_type');

        if ($this->customerId){
            $OrderModel = new OrderModel();
            $result = $OrderModel->getOrderByCustomerId($this->customerId);
            if (empty($result)){
                session('aftersale.customer_id', 0);
                return $this->redirect(url("shouindex"));
            }
            $this->tomb_typei = $result['tomb_typei'];
            $this->result_list =$result;

            $users = Db::name("user")->alias('u')->field('u.id,user_nickname,c.id dep_id,c.department_name')
                ->join('dj_department c','c.id=u.dept_id')->where(['u.user_type'=>2,'c.dept_type'=>4])->select();
            $dep = dept_per(4);
            $costset = Db::name('costset')->where(['id'=>1])->find();

            foreach ($users as $dk=>&$valued){
                $this->users_array[$valued['id']]=$valued['user_nickname'];
            }
            $this->tomb_num = $result['tomb_num'];
            $this->assign([
                'result'=>$result,
                'dep_list'=>$dep,
                'user_list'=>$users,
                'costset'=>$costset
            ]);
        }
    }

    public function login(){
        if($this->request->isPost()){
            $param= $this->request->param();
            $customer['token_customer']['customer_id'] = $param['id'];
            $customer['token_customer']['tomb_id'] = $param['tomb_id'];
            //登入成功页面跳转
            session('aftersale.customer_id', $param['id']);
            session('aftersale.tomb_id', $param['tomb_id']);
            session('aftersale.tomb_type', $param['tomb_type']);
            $this->result($customer);
        }
        $param= $this->request->param();
        if (isset($param['ajax']) && $param['ajax']==1){
            $buyer_cart = $param['buyer_cart'];
            $field = "ci.id,ci.buyer_name,ci.buyer_phone,ci.move_status";
            $field.= ",o.order_id,o.tomb_id,o.tomb_num,o.tomb_type,o.tomb_typei,o.status,o.deposit_state";
            $field.= ",p.tomb_region,p.tomb_address,p.tomb_bit_number";
            if(!empty($buyer_cart)){
                $res =  Db::name('customer_info')->alias('ci')
                    ->join('dj_order o','o.customer_id = ci.id')
                    ->join("dj_tombarea_information_product p","o.tomb_product_id = p.id")
                    ->where(['ci.customer_account'=>$buyer_cart,'ci.is_dy_mz'=>1,'ci.is_delete'=>0,'ci.move_status'=>1])
                    ->where(['o.is_delete'=>0])
                    ->field($field)
                    ->select();
                $this->result($res);
            }else{
                $this->result([],'','无用户');
            }
        }
        return $this->fetch();
    }
    public function outlogin(){
        session('aftersale', null);
        return $this->fetch('login');
    }

	public function index(){

        if ($this->customerId==0){
            return $this->fetch('login');
        }
        switch ($this->tomb_type) {
            case 1:
                return $this->fetch('index_commodity');
                break;
            case 2:
                return $this->fetch('index_arl');
                break;
            case 3:
                return $this->fetch('index_ecological');
                break;
            case 4:
                return $this->fetch('index_festival');
                break;
        }

		return $this->fetch('shouindex');
	}
	/*首页*/
	public function shouindex(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }
        $this->assign([
            'result'=>$this->result_list
        ]);


        switch ($this->tomb_type) {
            case 1:
                return $this->fetch('index_commodity');
                break;
            case 2:

                $user = Db::name("user")->where('id',cmf_get_current_admin_id())->find();

                $this->assign('user_if_sale',$user['if_sale']);
                return $this->fetch('index_arl');
                break;
            case 3:
                return $this->fetch('index_ecological');
                break;
            case 4:
                if ($this->result_list['tomb_typei'] == 1) {
                    return $this->fetch('index_festival_deposit');
                } else {
                    return $this->fetch('index_festival');
                }
                break;
        }
        return $this->fetch();
	}
	/*落葬业务*/
	public function burial(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }

        if ($this->tomb_type ==4 && $this->tomb_typei ==1){
            return $this->redirect(url("shouindex"));
        }
        if ($this->tomb_type==2){
            return $this->redirect(url("art"));
        }
        $buriedModel = new ServiceBuriedModel();
        if ($this->request->post()){
            $param = $this->request->param();
            $res = $buriedModel->doAddData($param,$this->result_list);
            if ($res!==false){
                return $this->success('提交成功',url("Aftersale/chooseGoods",['order_id'=>$this->result_list['order_id'],'customer_id'=>$this->customerId,'buried_id'=>$res,'tomb_id'=>$this->result_list['tomb_id']]));
            }else{
             return $this->error($buriedModel->getError());
            }
        }
        $buried_list =  $buriedModel->alias('sb')
            ->field('ad.*,sb.dealer_user,sb.handle_name,sb.service_status,sb.id')
            ->join('dj_archives_deceased ad','sb.id=ad.buried_id','left')
            ->where(['sb.order_id'=>$this->result_list['order_id']])->select();

        $deceased_list = Db::name('archives_deceased')
            ->where(['tomb_id'=>$this->result_list['tomb_id'],'customer_id'=>$this->customerId])->select();

        $buried_info = Db::name('service_buried')->where(['tomb_id'=>$this->result_list['tomb_id'],'customer_id'=>$this->customerId])->order('id desc')->find();
        $this->assign('buried_list',$buried_list);
        $this->assign('deceased',$deceased_list);
        $this->assign('handle',$buried_info);

		return $this->fetch();
	}

    /**
     *  落葬 商品
     * @return mixed|void
     */
	public function chooseGoods(){
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if (!empty($param['goods_id'])) {
                for ($i = 0; $i < count($param['goods_id']); $i++) {
                    $cate_name = Db::name("goods")->alias('g')
                        ->join('dj_cate c','g.cate_p_id = c.id')
                        ->where(['g.id' => $param['goods_id'][$i]])->field('c.cate_name')->find();
                    $arr = [
                        'type' =>2,
                        'order_id' => $param['order_id'],
                        'customer_id' => $param['customer_id'],
                        'deceased_id' => $param['deceased_id'],
                        'goods_id' => $param['goods_id'][$i],
                        'goods_name' => $param['goods_name'][$i],
                        'goods_price' => $param['goods_price'][$i],
                        'num' => $param['num'][$i],
                        'discount_price' => 0,
                        'total_price' => $param['goods_price'][$i] * $param['num'][$i],
                        'actual_amount' => $param['goods_price'][$i] * $param['num'][$i],
                        'add_user'=> cmf_get_current_admin_id(),
                        'add_time' => time(),
                        'buried_id' => $param['buried_id'],
                        'cate_name' => $cate_name['cate_name'],

                    ];
                    if (isset($param['id'])?$param['id']:''){
                        unset($arr['add_time']);
                        $result_id = Db::name('order_goods')->where(['id'=>$param['id']])->update($arr);
                    }else{
                        $result_id = Db::name('order_goods')->strict(false)->insertGetId($arr);
                    }
                }
            }else{

                Db::name('order_goods')->where(['order_id'=>$param['order_id'],'buried_id'=>$param['buried_id']])->delete();
            }
            return $this->success('提交成功',url("Aftersale/prints",['order_id'=>$param['order_id'],'buried_id'=>$param['buried_id']]));
        }
        $data = $this->request->param();

        $info_g = Db::name('order_goods')->where(['order_id'=>$data['order_id'],'type'=>2,'buried_id'=>$data['buried_id']])->select();

        //2为商品类型
        $where = array('d.type' => 2, 'd.is_delete' => 0, 'parent_id' => 0);
        //取库房数据
        $results_cate = Db::name("Cate")->alias('d')->where($where)->order('sort_order ASC,d.id DESC')->select();
        $this->assign("goods", $info_g);
        $this->assign("results_cate", $results_cate);
        $this->assign("order_id", $data['order_id']);
        $this->assign('buried_id',$data['buried_id']);
        $this->assign("deceased_id", isset($data['deceased_id']));
        $this->assign("customer_id", $data['customer_id']);
	    return $this->fetch();
    } //商品
    public function ajax_goods()
    {
        $cate_id = $this->request->param('cate_id');
        $where = ['d.type' => 0, 'd.is_delete' => 0, 'd.if_show' => 1, 'd.cate_p_id' => $cate_id];
        //取库房数据
        $results = Db::name("Goods")->alias("d")->field("d.id,d.goods_name,d.price,d.photos_url,stock")
            ->join("dj_room r", "r.id = d.room", "left")
            ->where($where)->order('d.id', 'DESC')->select();
        $this->result($results);
    }
	/* 落葬 缴费打证*/
	public function prints(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }

        if ($this->request->isPost()){
            $param = $this->request->param();
            $buried_id = $param['buried_id'];
            $project_id =[];
            $free_price = 0;
            $deal_price =0;
            $total_price = 0;
            foreach ($param['project'] as $key=>$value){
                $value['order_id']  = $this->result_list['order_id'];
                $value['buried_id'] = $buried_id;
                $value['add_time']  = time();
                $value['pay_id']    = 0;
                $total_price+=$value['total_price'];
                $deal_price+=$value['deal_price'];
                if ($value['free_price']!=0){
                    $free_price+=$value['free_price'];
                }elseif (!empty($value['discount_rate'])){
//                    (unit_price*num)*((100-discount_rate)/100);
                    $free_price+=$value['deal_price'] -$value['total_price'];
                    $value['deal_price'] =(100-$value['deal_price'])/100;
                }
                $project_id[] = Db::name('pay_project')->insertGetId($value);
            }
            $pay_ins = [
                'type'=>3,
                'itype'=>3,
                'order_id'=>$this->result_list['order_id'],
                'pay_sn'=>OrderPayLogModel::getselfPayNum('add_time','pay_sn','JS-'),//'JS'.date('YmdHi'),
                'tomb_id'=>$this->result_list['tomb_id'],
                'tomb_num'=>$this->result_list['tomb_num'],
                'tom_price'=>0,//购墓价格
                'discount_rate'=>0,//折扣
                'free_price'=>$free_price,//折扣
                'deal_price'=>$deal_price,//成交
                'total_price'=>$total_price,//应收金额
                'add_time'=>time(),//备注
                'handle'=>cmf_get_current_admin_id(),//收款人
                'pay_real_name'=>cmf_get_current_admin_id(),//收款人
                'status'=> 0,// 付款方式
                'other_id'=> $param['buried_id'],
                'customer_id' => $this->result_list['customer_id'],
            ];
            $pay_info = ServiceBuriedModel::where(['id'=>$param['buried_id']])->find();
            if ($pay_info['pay_id']){

                $pay_ins['real_name'] = $this->result_list['buyer_name'];
                $pay_ins['real_phone'] = $this->result_list['buyer_phone'];
                $rets = Db::name('order_pay_log')->where(['id'=>$pay_info['pay_id']])->update($pay_ins);
                $pay_id = $pay_info['pay_id'];
            }else{

                $pay_ins['real_name'] = $this->result_list['buyer_name'];
                $pay_ins['real_phone'] = $this->result_list['buyer_phone'];
                $rets =   Db::name('order_pay_log')->insertGetId($pay_ins);
                $pay_id = $rets;
            }
            if ($rets != false){
                ServiceBuriedModel::update(['pay_id'=>$pay_id],['id'=>$param['buried_id']]);
                Db::name('pay_project')->whereIn('project_id',$project_id)->update(['pay_id'=>$pay_id]);
                Db::name('order')->where(['order_id'=>$param['order_id']])->update(['status'=>1]);
                $this->success('提交成功',url('Aftersale/burial'));
            }else{
                $this->success('提交失败，请检查填写内容');
            }
        }
        $data = $this->request->param();
        $order_id =$data['order_id'];// $this->request->param('order_id',0);
        $buried_id = $data['buried_id'];//$this->request->param('buried_id',0);
        $deceased_list = ArchivesDeceasedModel::where(['order_id'=>$order_id,'buried_id'=>$buried_id])->select();

        $arr_list=[];
        foreach ($deceased_list as $key=>&$value){
            if ($value['type']==1){
                $project_info['project_name'] = '安葬费';
            }else{
                $project_info['project_name'] = '合葬费';
            }
            $project_info['project_unit'] = '位';
            $project_info['project_type'] = '服务';

            $project_info['unit_price']     = $value['funeral_price'];
            $project_info['total_price'] = $value['funeral_price'];
            $project_info['num'] = 1;
            $project_info['type'] = 0;
            $arr_list[] = $project_info;
        }


        $goods_info = Db::name('order_goods')->where(['order_id'=>$order_id,'buried_id'=>$buried_id,'type'=>2])->select();
        if ($goods_info){
            foreach ($goods_info as $key=>&$value){
                $g_info['project_name'] = $value['goods_name'];
                $g_info['project_unit'] = '个';
                $g_info['project_type'] = $value['cate_name'];
                $g_info['unit_price']   = $value['goods_price'];
                $g_info['total_price']  = $value['goods_price']*$value['num'];
                $g_info['num']          = $value['num'];
                $g_info['type'] = 1;
                $arr_list[] = $g_info;
            }
        }
        $this->assign([
            'result'=>$this->result_list,
            'arr_list'=>$arr_list,
            'buried_id'=>$buried_id
        ]);
		return $this->fetch();
	}

	/*维保业务*/
	public function maintenance(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }

        $WeibaoModel    = new ServiceWeibaoModel();
        if ($this->request->isPost()){
            $parem = $this->request->param();

             $res = $WeibaoModel->doAdd($parem,$this->result_list);
             if ($res){
                 $this->success('操作成功');
             }else{
                 $this->error($WeibaoModel->getError());
             }
        }


        $pro_id = $this->result_list['new_pro'];
        $old_pro = $this->result_list['old_pro'];
        $mb_arr=[];
        $result_pro_info = [];
        $pro_info = [];


        if ($this->result_list['tomb_type']==1){
            $old_pro_info= Db::name("product")->where(['id'=>$old_pro])->find();
//            exit(json_encode($old_pro_info));
            $m_info['id'] = $old_pro_info['id'];
            $m_info['pro_name'] = $old_pro_info['pro_name'].'('.$old_pro_info['pro_code'].')';
            $m_info['regulation_name'] = isset($old_pro_info['regulation'])?$this->regulation_arr[$old_pro_info['regulation']]:'';
            $m_info['pro_length'] = $old_pro_info['pro_length'].'mm*'.$old_pro_info['pro_width'].'mm*'.$old_pro_info['pro_height'].'mm';
            $m_info['address'] = '';
            $m_info['pro_code'] = $old_pro_info['pro_code'];
            $m_info['pro_photo'] = $old_pro_info['pro_photo'];
            $m_info['pro_price'] = $old_pro_info['pro_price'];
            $m_info['pro_photo_path'] = cmf_get_image_preview_url($old_pro_info['pro_photo']);
            $mb_arr[] = $m_info;

            $pro_info =  ProductInfoModel::where(['pro_id'=>$pro_id])->select();
        }else if ($this->result_list['tomb_type']==2){
            $tm_field = "tm.mb_id,tm.mb_name,tm.address,tm.tomb_id,tm.type,tm.mb_info_id";
            $tm_field .= ",pmb.id pro_id,pmb.pro_code,pmb.pro_name,pmb.pro_length,pmb.pro_width,pmb.pro_height,pmb.regulation,pmb.pro_photo,pmb.pro_photo,pmb.pro_price";
            $tomb_mb_list =  Db::name("tomb_mb")->alias('tm')->field($tm_field)
                ->join('dj_product_mb pmb','tm.mb_id = pmb.id')
                ->where(['tm.tomb_id'=>$this->result_list['tomb_id'],'tm.status'=>1,'tm.type'=>0])->select()->toArray();

             $tomb_mb_list_fujian =  Db::name("tomb_mb")->alias('tm')->field('pmi.*')
                            ->join('product_mb_info pmi','tm.mb_info_id = pmi.id')
                            ->where(['tm.tomb_id'=>$this->result_list['tomb_id'],'tm.status'=>1,'tm.type'=>7])->select()->toArray();


            foreach ($tomb_mb_list as $km=>&$vals){
                $infoData_info = [];
                $infoData =  Db::name("product_mb_info")->where(['pro_id' => $vals['pro_id']])->select()->toArray();
                 $arr = array_merge($infoData,$tomb_mb_list_fujian);

                foreach ($arr as $key=>&$val){
                    if ($this->result_list['is_bxq_status']==-1){
                        $val['is_expired'] = '超期';
                        $val['is_expired_checked'] = '';
                    }else{
                        $val['is_expired'] = '期内';
                        $val['is_expired_checked'] = 'checked';
                    }
                    $val['admin_name'] = cmf_get_admin_name();
                    $infoData_info[] = $val;
                }
                $m_info['id'] = $vals['pro_id'];
                $m_info['pro_name'] = $vals['mb_name']."【".$vals['pro_name'].'('.$vals['pro_code'].')】';
                $m_info['regulation_name'] = $this->regulation_arr[$vals['regulation']];
                $m_info['pro_length'] = $vals['pro_length'].'mm*'.$vals['pro_width'].'mm*'.$vals['pro_height'].'mm';
                $m_info['address'] = $vals['address'];
                $m_info['pro_code'] = $vals['pro_code'];
                $m_info['pro_photo'] = $vals['pro_photo'];
                $m_info['pro_price'] = $vals['pro_price'];
                $m_info['pro_photo_path'] = cmf_get_image_preview_url($vals['pro_photo']);
                $m_info['pro_part_json'] = json_encode($infoData_info);
                $mb_arr[]=$m_info;
            }
            if ($mb_arr){
                $pro_info  =  Db::name("product_mb_info")->where(['pro_id' => $mb_arr[0]['id']])->select();
            }

//            exit(json_encode($mb_arr));

        }else if ($this->result_list['tomb_type']==3){
        }else if ($this->result_list['tomb_type']==4){
        }

        foreach ($pro_info as $key=>&$val){
            if ($this->result_list['is_bxq_status']==-1){
                $val['is_expired'] = '超期';
                $val['is_expired_checked'] = '';
            }else{
                $val['is_expired'] = '期内';
                $val['is_expired_checked'] = 'checked';
            }
            $val['admin_name'] = cmf_get_admin_name();
            $result_pro_info[] = $val;
        }
        $conventional = $this->array_conventional();

        $records = $WeibaoModel->where(['tomb_id'=>$this->tombId,'customer_id'=>$this->customerId])->paginate(10);
        $users = Db::name("user")->alias('u')->field('u.id,user_nickname,c.department_name')
            ->join('dj_department c','c.id=u.dept_id')
            ->where(['u.user_type'=>2,'c.dept_type'=>4])
            ->select();


        $this->assign('tomb_list',$mb_arr);

        $this->assign("userlist", $users);
        $this->assign("userlistjson", json_encode($users));
        $this->assign('pro_info',$result_pro_info);
        $this->assign('conventional',$conventional);
        $this->assign('records',$records);
        $this->assign('cate_id',$this->result_list['tomb_type']);
		return $this->fetch();
	}
	/*迁墓业务*/
	public function move(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }
		return $this->fetch();
	}
	/*艺术墓*/
	public function art(){
        if ($this->request->post()){
            $param = $this->request->param();

            $buriedModel = new ServiceBuriedModel();
            $res = $buriedModel->doAddYsData($param,$this->result_list);
            if ($res!=false){
                return $this->success('提交成功',url("Aftersale/chooseGoods",['order_id'=>$this->result_list['order_id'],'customer_id'=>$this->customerId,'buried_id'=>$res,'tomb_id'=>$this->result_list['tomb_id']]));
            }else{
                return $this->error($buriedModel->getError());
            }
        }

        if ($this->customerId==0){
            return $this->fetch('login');
        }
        if ($this->tomb_type ==4 && $this->tomb_typei ==1){
            return $this->redirect(url("shouindex"));
        }
        $buried_list =  Db::name('service_buried')->alias('sb')
            ->join('dj_archives_deceased ad','sb.id=ad.buried_id','left')
            ->where(['sb.order_id'=>$this->result_list['order_id']])->select();

        $buried_info = Db::name('service_buried')->where(['tomb_id'=>$this->result_list['tomb_id'],'customer_id'=>$this->customerId])->order('id desc')->find();
        $this->assign('buried_list',$buried_list);
        $this->assign('handle',$buried_info);

        if ($this->tomb_type !=2){
            $deceased_list = Db::name('archives_deceased')
                ->where(['tomb_id'=>$this->result_list['tomb_id'],'customer_id'=>$this->customerId])->select();

            $buried_info = Db::name('service_buried')->where(['tomb_id'=>$this->result_list['tomb_id'],'customer_id'=>$this->customerId])->order('id desc')->find();
            $this->assign('buried_list',$buried_list);
            $this->assign('deceased',$deceased_list);
            $this->assign('handle',$buried_info);
            return $this->fetch('burial');
        }else {
            $tm_field = "tm.mb_id,tm.mb_name,tm.address,tm.tomb_id,tm.type,tm.mb_info_id";
            $tm_field .= ",pmb.id pro_id,pmb.pro_code,pmb.pro_name,pmb.pro_length,pmb.pro_width,pmb.pro_height,pmb.regulation,pmb.pro_photo,pmb.pro_photo,pmb.pro_price";
            $tomb_mb_list = Db::name("tomb_mb")->alias('tm')->field($tm_field)
                ->join('dj_product_mb pmb', 'tm.mb_id = pmb.id')
                ->where(['tm.tomb_id' => $this->result_list['tomb_id'], 'tm.status' => 1,'type'=>0])->select();

            $mb_arr = [];
            foreach ($tomb_mb_list as $km => &$vals) {
                $m_info['id'] = $vals['mb_id'];
                $m_info['pro_name'] = $vals['mb_name'] .'【' .$vals['address'].'/'.$vals['pro_name'] . '/' . $vals['pro_code'] . '】';
                $m_info['regulation_num'] = $vals['regulation'];
                $m_info['regulation_name'] = $this->regulation_arr[$vals['regulation']];
                $m_info['pro_length'] = $vals['pro_length'] . 'mm*' . $vals['pro_width'] . 'mm*' . $vals['pro_height'] . 'mm';
                $m_info['pro_code'] = $vals['pro_code'];
                $m_info['address'] = $vals['address'];
                $m_info['pro_photo'] = $vals['pro_photo'];
                $m_info['pro_photo_path'] = cmf_get_image_preview_url($vals['pro_photo']);
                $mb_arr[] = $m_info;
            }
            $this->assign('tomb_list', $mb_arr);
            return $this->fetch();
        }
	}

	/*寄存业务*/
	public function check(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }
        if ($this->tomb_type!=4 && $this->tomb_typei !=1){
            return $this->redirect(url("shouindex"));
        }
        if ($this->request->isPost()){
            $param = $this->request->param();
            $model = new ServiceDepositModel();
            $res = $model->doAddData($param,$this->result_list);
            if ($res!=false){
                return $this->success('提交成功');
            }else{
                return $this->error($model->getError());
            }
        }
        $deceased_list = Db::name('archives_deceased')->alias('ad')
            ->field('ad.*,od.deposit_time,od.id deposit_id')
            ->leftJoin('dj_order_deposit od','od.id = ad.deposit_id')
            ->where(['ad.tomb_id'=>$this->result_list['tomb_id'],'od.customer_id'=>$this->customerId])->select();

        if (empty($deceased_list)){
            return $this->fetch('index');
        }else{
            // 从服务管理的表中取数据
            $service = ServiceDepositModel::where(['tomb_id'=>$this->result_list['tomb_id'],'type'=>1,'customer_id'=>$this->customerId])
                ->where("service_status", "neq","3")->find();
            // 查询审核的信息
            if($service){
                $service['move_time'] = date('Y-m-d H:i');
                $apinfo = Db::name('approval')->where(['form_type'=>'2','detail_type'=>8,'form_id'=>$service['id']])->find();
            }else{
                $apinfo = [];
            }
            $this->assign("approvialinfo",$apinfo);
            $result_jc = Db::name('order_deposit')->where(['customer_id'=>$this->customerId,'status'=>1])->find();

            $this->assign('service',$service);
            $this->assign('deceased_list',$deceased_list);
            $this->assign('result_jc',$result_jc);

            $this->result_list['gm_start_time'] =  unixtime_to_date($result_jc['deposit_time'],'Y年m月d日');
            $this->result_list['deposit_storage'] = $result_jc['storage_time'];

            if ($result_jc['deposit_end_time'] > time()){
                $this->result_list['deposit_end_time'] = unixtime_to_date($result_jc['deposit_end_time'],'Y年m月d日').'到期';
                $this->result_list['deposit_status'] = '未到期';
            }else{
                $int = time() - $result_jc['deposit_end_time'];
                $str = sprintf('%d天', floor($int / 86400));
                $this->result_list['deposit_end_time'] = '已超'.$str;
                $this->result_list['deposit_status'] = '已到期';
            }

            $send_info = OrderDepositSendModel::where(['mw_id'=>$this->tombId])->order('id desc')->find();


            $this->result_list['deposit_status_mw'] = '全部寄存';
            $this->assign(  'result',$this->result_list);

        }

//        exit(json_encode($deceased_list));
		return $this->fetch();
	}
	public function renewal()
    {
        if ($this->request->isPost()){
            $parm = $this->request->param();
            $model = new OrderDepositSendModel();
            $res = $model->doAddData($parm,$this->result_list);
            if ($res !=false){
                return $this->success('提交成功，请尽快前往财务缴费');
            }else{
                return $this->error($model->getError());
            }
        }
    }
	/*退墓业务*/
	public function back(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }
        if ($this->result_list['col_status'] != 5){
            $this->success("只有购买未使用的墓位可以办理退墓业务！", url("shouindex"));
        }
        if ($this->tomb_type ==4 && $this->tomb_typei ==1){
            return $this->redirect(url("shouindex"));
        }
        $model = new RetreatTombModel();
	    if ($this->request->isPost()){
	        $parem= $this->request->param();
            $restel = $model->doAddDate($parem,$this->customerId);
	        if ($restel!=false){
	            $this->success('提交成功，待审核中',url('back'));
            }else{
	            $this->error($model->getError());
            }
        }
        $res_pay = Db::name('order_pay_log')->where(['status'=>1,'tomb_id'=>$this->tombId,'customer_id'=>$this->customerId])->find();
//        $res_pay = $model->where(['mw_id'=>$this->tombId])->find();
        $res_retreat = $model->alias('rt')->field('rt.*,spi.id approval_id,spi.apply_time,spi.approval_status,spi.approval_desc,spi.approval_user,spi.approval_time')
            ->leftJoin('dj_approval spi','rt.id = spi.form_id')
            ->where(['rt.mw_id'=>$this->tombId,'spi.form_type'=>2,'spi.detail_type'=>4,'rt.customer_id'=>$this->customerId])->find();

        $pay_real_name = cmf_get_admin_name($res_pay['pay_real_name']);
        $refund_reason = [
            '1'=>'产品外观原因',
            '2'=>'产品质量原因',
            '3'=>'环境服务原因',
            '4'=>'客户原因',
            '5'=>'竞争原因',
            '6'=>'其他原因',
        ];
        $this->assign('refund_reason',$refund_reason);
        $this->assign('pay_type',cart_type('pay'));
        $this->assign('pay_info',$res_pay);
        $this->assign('retreat',$res_retreat);
        $this->assign('approval_id',isset($res_retreat['approval_id'])?$res_retreat['approval_id']:'');
        $this->assign('approval_id',isset($res_retreat['approval_id'])?$res_retreat['approval_id']:'');
        $this->assign('feature_xq',isset($res_retreat['approval_id'])?$res_retreat['approval_id']:'feature');
        $this->assign('feature_x',isset($res_retreat['approval_id'])?($res_retreat['approval_id'] !=''?"feature":""):'');
        $this->assign('apply_time',isset($res_retreat['apply_time'])?date('Y-m-d H:i:s',$res_retreat['apply_time']):'');
        $this->assign('pay_real_name',$pay_real_name);
        $this->assign('add_time',date("Y-m-d"),time());

		return $this->fetch();
	}

	// 管理费业务
	public function protect(){
        if ($this->customerId==0){
            return $this->redirect(url("login"));
        }
        if ($this->tomb_type ==4 && $this->tomb_typei ==1){
            return $this->redirect(url("shouindex"));
        }
        $ProtectPayModel = new ProtectPaymentModel();
        if ($this->request->isPost()){
            $parem = $this->request->param();
           $res = $ProtectPayModel->doAddData($this->result_list,$parem);
             if ($res !=false){
                 $this->success("添加成功！", url("protect"));
             }else{
                 $this->error($ProtectPayModel->getError());
             }
        }
        $results = $ProtectPayModel ->where(['mw_id'=>$this->tombId,'customer_id'=>$this->customerId])->order('id desc')->select();


        $this->assign("protect_payment", $results);
        $this->assign("pay_time", date("Y-m-d H:i", time()));

        return $this->fetch();
    }


	/*证件管理业务*/
	public function paperwork(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }
        $changeModel = new ChangeModel();
        if ($this->request->post()){
            $param = $this->request->param();

            if($param['types'] == "change"){
                $info = $param['change'];
            }else{
                $info = $param['loss'];
            }
            $errMsg = cmf_check_verification_code($info['phone'],$info['verification_code'],true);
            if (!empty($errMsg)) {
                $this->error($errMsg);
            }
            unset($info['code']);
            $info['status'] = $param['status'];

            $res = $changeModel->doAddData($info,$this->result_list);
            if ($res!==false){

                return $this->success('提交成功',url("Aftersale/paperwork",['order_id'=>$this->result_list['order_id'],'customer_id'=>$this->customerId,'buried_id'=>$res,'tomb_id'=>$this->result_list['tomb_id']]));
            }else{
                return $this->error($changeModel->getError());
            }
        }
        // 获取最新一条未提交审核数据
        $change = Db::name('change')
            ->field('*')
            ->where(['type'=>1,'status'=>0])
            ->limit(1)
            ->order("id desc")
            ->find();
        if(!$change){
            $change['change_time'] = time();
            $change['name'] = "";
            $change['sex'] = "1";
            $change['phone'] = "";
            $change['cart_type'] = "1";
            $change['cart_ID'] = '';
            $change['customer_address'] = '';
            $change['change_reason'] = 0;
        }
        $this->assign('change',$change);
        $loss = Db::name('change')
            ->field('*')
            ->where(['type'=>1,'status'=>0])
            ->limit(1)
            ->order("id desc")
            ->find();
        $this->assign('loss',$loss);

        // 获取挂失工本费
        $cost = Db::name('costset')
            ->field('id_cost')
            ->limit(1)
            ->order("id desc")
            ->find();
        $this->assign('id_cost',$cost['id_cost']);

        // 获取最新一条数据的审核信息
        $info = Db::name('change')
            ->field('*')
            ->where('status','>',0)
            ->limit(1)
            ->order("id desc")
            ->find();
        $where3 = ['detail_type'=>6,'form_id'=>$info['id']];
        $approval = Db::name('approval')
                    ->field('*')
                    ->where(['detail_type'=>5,'form_id'=>$info['id']])
                    ->whereOr(function ($q) use($where3){$q->where($where3);})
                    ->find();
        $this->assign('approval',$approval);
        // 经办人
        $this->assign('add_user',cmf_get_admin_name(cmf_get_current_admin_id()));
        // 历史记录
        $log_list = Db::name('change')->alias('ad')
            ->field('ad.*,u.user_nickname,c.cart_upload as old_cart_upload')
            ->leftJoin('dj_user u','u.id = ad.add_user')
            ->leftJoin('dj_customer_info c','c.id = ad.customer_id')
            ->where(['ad.customer_id'=>$this->customerId])
            ->select()->toArray();
        foreach ($log_list as $key => $val){
            $log_list[$key]['type_name'] = $val['type'] == 1?"变更":"挂失";
            if($val['type'] == 1){
                if($val['change_reason'] == 0){
                    $log_list[$key]['change_reason'] = "（注册人）已故";
                }elseif ($val['change_reason'] == 1){
                    $log_list[$key]['change_reason'] = "亲属变更";
                }elseif ($val['change_reason'] == 1){
                    $log_list[$key]['change_reason'] = "配偶变更";
                }else{
                    $log_list[$key]['change_reason'] = "子女变更";
                }
            }else{
                $log_list[$key]['change_reason'] = $val['change_reason'] == 0?"损毁":"遗失";
            }

        }
        $this->assign('log_list',$log_list);
        // 逝者信息
        $deceased_list = Db::name('archives_deceased')->alias('d')
            ->field('d.*,s.service_status,s.id,s.dealer_user')
            ->leftJoin('dj_service_buried s','s.id = d.buried_id')
            ->where(['d.tomb_id'=>$this->tombId,'d.customer_id'=>$this->customerId])
            ->select()->toArray();
        foreach ($deceased_list as $k => $v){
            $deceased_list[$k]['gender'] = $v['gender'] == 1?"男":"女";
            $deceased_list[$k]['convergence_type'] = $v['convergence_type'] == 1?"骨灰":"骨殖";
            $deceased_list[$k]['type'] = $v['type'] == 1?"购买":"寄存";
            if($v['service_status'] == 1){
                $deceased_list[$k]['service_status'] = "未确认";
            }elseif($v['service_status'] == 2){
                $deceased_list[$k]['service_status'] = "已确认";
            }elseif($v['service_status'] == 3){
                $deceased_list[$k]['service_status'] = "已完成";
            }else{
                $deceased_list[$k]['service_status'] = "-";
            }
        }
        $this->assign('deceased_list',$deceased_list);
        $this->assign('tomb_typei',$this->result_list['tomb_typei']);

		return $this->fetch();
	}
	public function paperloss(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }
		return $this->fetch();
	}
	/*墓碑刻制*/
	public function carve(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }

        $carveModel = new CarveModel();
        if ($this->request->post()){
            $param = $this->request->param();
            $res = $carveModel->doAddData($param,$this->result_list);
            if ($res!==false){

                return $this->success('提交成功',url("Aftersale/carve",['order_id'=>$this->result_list['order_id'],'customer_id'=>$this->customerId,'buried_id'=>$res,'tomb_id'=>$this->result_list['tomb_id']]));
            }else{
                return $this->error($carveModel->getError());
            }
        }
        $info = Db::name('carve')->where(['tomb_id'=>$this->result_list['tomb_id'],'customer_id'=>$this->customerId])->order('id desc')->limit(1)->find();

        $insc_info = Db::name('carve_insc')
            ->where(['carve_id'=>$info['id']])->find();
        if(!empty($insc_info['pay_time'])){
            $insc_info['pay_time'] = date('Y/m/d',$insc_info['pay_time']);
        }

        $image_info = Db::name('carve_image')
            ->where(['carve_id'=>$info['id']])->find();
        if(!empty($image_info['pay_time'])){
            $image_info['pay_time'] = date('Y/m/d',$image_info['pay_time']);
        }

        $gold_info = Db::name('carve_gold')
            ->where(['carve_id'=>$info['id']])->find();
        if(!empty($gold_info['pay_time'])){
            $gold_info['pay_time'] = date('Y/m/d',$gold_info['pay_time']);
        }

        $this->assign('data',$info);
        $this->assign('insc',$insc_info);
        $this->assign('image',$image_info);
        $this->assign('gold',$gold_info);

        $lists = Db::name('carve')->where(['tomb_id'=>$this->result_list['tomb_id'],'customer_id'=>$this->customerId])->order('id desc')->select()->toArray();

        $result_carve =[];
        foreach ($lists as $key=>&$val){
            $insc_list = Db::name('carve_insc')->where(['carve_id'=>$val['id']])->select();
            $val['insc_list']   = $insc_list;
            $gold_list = Db::name('carve_gold')->where(['carve_id'=>$val['id']])->select();
            $val['gold_list']   =  $gold_list;
            $image_list = Db::name('carve_image')->where(['carve_id'=>$val['id']])->select();
            $val['image_list']   =  $image_list;
            $result_carve[] = $val;
        }
//        exit(json_encode($result_carve));
        $this->assign('result_carve',$result_carve);

        if(!empty($lists)){

            $insc_list = Db::name('carve_insc')->where(['carve_id'=>array('in',implode(',',array_column($lists,'id')))])->select();
            $gold_list = Db::name('carve_gold')->where(['carve_id'=>array('in',implode(',',array_column($lists,'id')))])->select();
            $image_list = Db::name('carve_image')->where(['carve_id'=>array('in',implode(',',array_column($lists,'id')))])->select();
        }else{
            $insc_list = [];
            $gold_list = [];
            $image_list = [];
        }
        if ($this->tomb_type !=2){
            $pro_info = Db::name('product')->where(['id'=> $this->result_list['new_pro']])->find();
            $m_info['id'] = $pro_info['id'];
            $m_info['pro_name'] = $pro_info['pro_name'];
            $mb_arr[] = $m_info;
        }else{
            $tm_field = "tm.mb_id,tm.mb_name,tm.address,tm.tomb_id,tm.type,tm.mb_info_id";
            $tm_field .= ",pmb.id pro_id,pmb.pro_code,pmb.pro_name,pmb.pro_length,pmb.pro_width,pmb.pro_height,pmb.regulation,pmb.pro_photo,pmb.pro_photo,pmb.pro_price";
            $tomb_mb_list = Db::name("tomb_mb")->alias('tm')->field($tm_field)
                ->join('dj_product_mb pmb', 'tm.mb_id = pmb.id')
                ->where(['tm.tomb_id' => $this->result_list['tomb_id'], 'tm.status' => 1,'type'=>0])->select();
            $mb_arr = [];
            foreach ($tomb_mb_list as $km => &$vals) {
                $m_info['id'] = $vals['mb_id'];
                $m_info['pro_name'] = $vals['mb_name'] .'【位置：' .$vals['address']. '】';
                $mb_arr[] = $m_info;
            }
        }
        $this->assign('tomb_list',$mb_arr);

        $this->assign('insc_list',$insc_list);
        $this->assign('gold_list',$gold_list);
        $this->assign('image_list',$image_list);

        return $this->fetch();
	}
	/*工程首页*/
	public function sale(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }
		return $this->fetch();
	}
	/*墓位产品信息*/
	public function add(){
        $parentid = $this->request->param('parentid', 0, 'intval');
        $id = $this->request->param('tid', 0, 'intval');
        $this->assign("id",$id);
        $this->assign("parentid",$parentid);
		return $this->fetch();
	}


	public function art_product(){
        // 石材种类
        $this->getALlOption();

        $id = $this->request->param("id");
        $type = $this->request->param('type');
        $where = array(
            'id' => $id
        );
        $result = Db::name("product_mb")->where($where)->find();
        $this->assign($result);
        // 详情
        $infowhere = array(
            'mb_id' => $id,
            'itype' => 1
        );
        $infoData = Db::name("product_mb_info")->where($infowhere)->select();
        $this->assign('infoData', $infoData);
        // 基础
        $basewhere = array(
            'mb_id' => $id,
            'itype' => 2
        );
        $baseData = Db::name("product_mb_info")->where($basewhere)->select();
        $this->assign('baseData', $baseData);
        // 盖板
        $platewhere = array(
            'mb_id' => $id,
            'itype' => 3
        );
        $plateData = Db::name("product_mb_info")->where($platewhere)->select();
        $this->assign('plateData', $plateData);

        // 栏杆
        $railwhere = array(
            'mb_id' => $id,
            'itype' => 4
        );
        $railData = Db::name("product_mb_info")->where($railwhere)->select();
        $this->assign('railData', $railData);

        // 附件
        $annexwhere = array(
            'mb_id' => $id,
        );
        $annexData = Db::name("product_mb_annex")->where($annexwhere)->select();
        $this->assign('annexData', $annexData);
        // echo Db::name("product_mb_annex")->getLastSql();
        $this->assign('type_mb', $type);
        return $this->fetch();
    }
    /**
     * 下拉数据
     */
    public function getALlOption()
    {
        $cate_type = Db::name("stuff")->alias('s')->field("s.id,concat(c.cate_name,'-',s.stuff_name) as name")->join("dj_cate c", "c.id = s.cate_id", "left")->select();
        $this->assign("cate_type", $cate_type);
        $this->assign("cateJson", json_encode($cate_type));
        // 所有产品库
        $allData = Db::name("product")->field("id,pro_name as name")->select();
        $this->assign("allData", $allData);
        // 附件
        $annex = Db::name("annex")->field("id,annex_name as name")->select();
        $this->assign("annex", $annex);
        $this->assign("annexJson", json_encode($annex));
    }

    /*不良记录的查询列表*/
    public function badindex()
    {
        if ($this->customerId==0){
            return $this->fetch('login');
        }
        $results = Db::name("badlog")->alias("b")->field("b.*,b.id bid,u.user_nickname")
            ->leftJoin("user u", "u.id=b.add_user" )
            ->where("is_delete","0")
            ->where('tomb_num', $this->tomb_num)
//            ->where('tomb_num', "ys1001")
            ->paginate(10);
        $page = $results->render();
        $this->assign("results", $results);
        $this->assign("page", $page);

        return $this->fetch();
    }

    /*不良记录--查看详情*/
    public function badgetdetail()
    {
        $id = $this->request->param('id');
        $result = Db::name("badlog")->alias("b")->field("u.user_nickname,b.*")
            ->leftJoin("user u", "u.id=b.add_user")
            ->where('b.id', $id)
            ->find();
        $result['add_time'] = date('Y/m/d H:i:s',$result['add_time']);
        $this->assign($result);

        // 获取购买人信息
        $this->assign("results", $this->result_list);
        return $this->fetch();
    }
    /*不良记录-删除数据*/
    public function baddelete()
    {
        $id = $this->request->param("id");

        $saveData =  Db::name("badlog")
            ->where('id', $id)
            ->find();
        $saveData['is_delete'] ='1';
        Db::name("badlog")->update($saveData);

        $this->success("删除成功", url("Aftersale/badindex"));
    }
    /*不良记录-解锁或锁定*/
    public function badlock()
    {
        $id = $this->request->param("id");
        $lock_status = $this->request->param("lock_status");

        $saveData =  Db::name("badlog")
            ->where('id', $id)
            ->find();
        $saveData['lock_status'] = $lock_status==1 ? 2: 1 ;
        Db::name("badlog")->update($saveData);

        $this->success("操作成功", url("Aftersale/badindex"));
    }

    /**
     * @param int $t 1:历史记录 2 历史查看业务内容 3：， 4： 查看维修结果 5 查看上次完成 6 办理人 业务内容；7： 8：购墓人
     */
    public function ajax($t=0){

        $type = $this->request->get("t", 0);
        $page = $this->request->get("page", 0);
        $limit = $this->request->get("limit", 10);
        $WeibaoModel    = new ServiceWeibaoModel();
        $MaintenanceProjectModel    = new MaintenanceProjectModel();

        if ($type==1){
            $list = $WeibaoModel->where(['tomb_id'=>$this->tombId,'customer_id'=>$this->customerId])->order('id desc')->limit($page,$limit)->select();
            $total =$WeibaoModel->where(['tomb_id'=>$this->tombId,'customer_id'=>$this->customerId])->count();

            foreach ($list as $k => &$val) {
                $val['register_time'] = date('Y.m.d',$val['register_time']);
                $value['service_status'] = $val['service_status']==1?'未确认':($val['service_status']==2?'已确认':($val['service_status']==3?"已完成":$val['service_status']==4?"已上传":''));
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }elseif ($type==2){
            $id = $this->request->param('id');
            $mb = $this->request->param('mb',0);
            if ($mb==1){
                $list = $MaintenanceProjectModel->alias('wp')
                    ->field('wp.*,pm.pro_name,u.user_nickname,d.department_name')
                    ->leftJoin('dj_user u','wp.dep_id = u.id')
                    ->leftJoin('dj_department d','u.dept_id = d.id')
                    ->leftJoin('dj_product_mb pm','wp.pro_id = pm.id')
//                    ->leftJoin('dj_maintenance_project mp','wp.id = mp.wb_id')
                    ->where(['wp.wb_id'=>$id])->select();

            }else{
                $list = $MaintenanceProjectModel->alias('wp')
                    ->field('wp.*,u.user_nickname,d.department_name')
                    ->leftJoin('dj_user u','wp.dep_id = u.id')
                    ->leftJoin('dj_department d','u.dept_id = d.id')
                    ->where(['wp.wb_id'=>$id])->select();
            }
            foreach ($list as $k=>&$value){
                $value['deliver_time'] = date('Y-m-d',$value['deliver_time']);
                $value['dep_id'] = $this->users_array[$value['dep_id']];
            }
            return $this->result($list);
        }elseif ($type==3){
            $id = $this->request->param('id');
            $list = $MaintenanceProjectModel->where(['wb_id'=>$id])->limit($page,$limit)->select();
            $total =$MaintenanceProjectModel->where(['wb_id'=>$id])->count();

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }elseif ($type==4){

            $id = $this->request->param('id');
            $list = Db::name('service_confirm')->where(['service_id'=>$id,'task_type'=>'weibao'])->select();

            return $this->result($list);
        }elseif ($type==5){
            //
            $id = $this->request->param('id');
            $type = $this->request->param('type');
            $wb_id = $MaintenanceProjectModel->where(['part_id'=>$id,'mw_id'=>$this->tombId,'type'=>$type])->column('wb_id');
            $list = $WeibaoModel->alias("wb")
                ->field("wb.*,u.user_nickname,d.department_name")
                ->leftJoin('dj_maintenance_project mp','mp.wb_id = wb.id')
                ->leftJoin('dj_user u','mp.dep_id = u.id')
                ->leftJoin('dj_department d','u.dept_id = d.id')
                ->whereIn('wb.id',$wb_id)
                ->select();
            foreach ($list as $k=>&$value){
                $value['register_time'] = date('Y-m-d',$value['register_time']);
                $value['service_status'] = $value['service_status']==1?'未确认':($value['service_status']==2?'已确认':($value['service_status']==3?"已完成":$value['service_status']==4?"已上传":''));
            }
            return $this->result($list);
        }elseif ($type==6){
//            $mwid = $this->request->param('mwid');
            $mbid = $this->request->param('mb_id');
            $deceased_list = ArchivesDeceasedModel::where(['tomb_id'=>$this->result_list['tomb_id'],'mb_id'=>$mbid,'customer_id'=>$this->customerId])->order('deceased_id asc ')->select();

            return $this->result($deceased_list);
        }elseif ($type==7){
            $id = $this->request->param('id');
            $buried = Db::name('service_buried')->where(['id'=>$id])->select();

            return $this->result($buried);
        }elseif ($type==8){
            $id = $this->request->param('id');

            $customer = Db::name('change')->alias("c")
                ->field("i.*,c.add_time,u.user_nickname")
                ->leftJoin('dj_customer_info i','i.id = c.customer_id')
                ->leftJoin('dj_user u','u.id = c.add_user')
                ->where(['c.id'=>$id,'c.customer_id'=>$this->customerId])->select()->toArray();
            foreach ($customer as $k=>&$value){
                $customer[$k]['add_time'] = date('Y-m-d',$value['add_time']);
                $customer[$k]['buyer_sex'] = $value['buyer_sex']==1?'男':'女';
                $customer[$k]['cart_type'] = $value['cart_type']==1?'身份证':'其他';
                $customer[$k]['cart_upload'] = $value['cart_upload']?"/upload/".$value['cart_upload']:'';
            }
            return $this->result($customer);
        }elseif ($type==9){
            $id = $this->request->param('id');

            $customer = Db::name('customer_info')
                ->where('id',$id)->select()->toArray();
            foreach ($customer as $k=>&$value){
                $customer[$k]['add_time'] = date('Y-m-d',$value['add_time']);
                $customer[$k]['buyer_sex'] = $value['buyer_sex']==1?'男':'女';
                $customer[$k]['cart_type'] = $value['cart_type']==1?'身份证':'其他';
                $customer[$k]['cart_upload'] = $value['cart_upload']?"/upload/".$value['cart_upload']:'';
            }

            return $this->result($customer);
        }elseif ($type==10){
            // 寄出
            $ServiceDepositModel = new ServiceDepositModel();
            $OrderDepositModel = new OrderDepositModel();
            $list = $ServiceDepositModel->where(['tomb_id'=>$this->tombId,'customer_id'=>$this->customerId,'type'=>1])->order('id desc')->limit($page,$limit)->select();
            $total =$ServiceDepositModel->where(['tomb_id'=>$this->tombId,'customer_id'=>$this->customerId])->count();

            $array_list=[];
            foreach ($list as $k => &$val) {
                $deposit_info = $OrderDepositModel->where(['id'=>$val['deposit_id']])->find();
                $ArchivesDeceased_info = ArchivesDeceasedModel::where(['servicedeposit_id'=>$val['id']])->find();
                $arr_info['deposit_time'] =  date('Y-m-d H:i:s',$deposit_info['deposit_time']);;
                $arr_info['convergence_type'] =  $ArchivesDeceased_info['convergence_type']==1?"骨灰":($ArchivesDeceased_info['convergence_type']==2?'骨殖':'');
                $arr_info['convergence_type'] =  $ArchivesDeceased_info['convergence_type']==1?"骨灰":($ArchivesDeceased_info['convergence_type']==2?'骨殖':'');
                $arr_info['cremation_certificate_img'] = cmf_get_image_preview_url($ArchivesDeceased_info['cremation_certificate']);
                $arr_info['url_file_original'] = cmf_get_image_preview_url($val['url_file_original']);
                $arr_info['deposit_time_out'] =   date('Y-m-d H:i:s',$val['add_time']);;
                $arr_info['handle_name'] =   $val['handle_name'];

                $arr_info['deceased']['deceased_name'] = $ArchivesDeceased_info['deceased_name'];
                $arr_info['deceased']['gender'] =  $ArchivesDeceased_info['gender']==1?"男":($ArchivesDeceased_info['gender']==2?"女":"");
                $arr_info['deceased']['date_birth'] = $ArchivesDeceased_info['date_birth'];
                $arr_info['deceased']['date_death'] = $ArchivesDeceased_info['date_death'];
                $arr_info['deceased']['relationship_users'] = !empty($ArchivesDeceased_info['relationship_users'])?empty($ArchivesDeceased_info['relationship_users']):'';

                $arr_info['handle']['buyer_name'] = $val['dealer_user'];
                $arr_info['handle']['buyer_sex'] = $val['dealer_sex']==1?"男":($val['dealer_sex']==2?"女":"");
                $arr_info['handle']['buyer_phone'] = $val['dealer_phone'];
                $arr_info['handle']['relationship'] = $val['relationship'];
                $arr_info['handle']['cart_type'] = cart_type('cart', $val['dealer_cart_type']);
                $arr_info['handle']['cart_num'] = $val['dealer_cart_num'];
                $arr_info['handle']['cart_address'] = $val['dealer_address'];
                $arr_info['handle']['file_url'] = cmf_get_image_preview_url($val['url_cart_file']);
                $arr_info['handle']['handle_name'] =  $val['handle_name'];
                $arr_info['handle']['handle_time'] =  date('Y-m-d H:i:s',$val['add_time']);

                $arr_info['dealer_user'] = $val['dealer_user'];
                $arr_info['dead_name'] = $val['dead_name'];
                $arr_info['confirm_content'] = $val['confirm_content'];
                $arr_info['add_time'] = date('Y-m-d H:i:s',$val['add_time']);

                $arr_info['submit_status_name'] = $val['submit_status']==1?'未确认':($val['submit_status']==2?'已确认':($val['submit_status']==3?"已完成":$val['submit_status']==4?"已上传":''));
                $array_list[]= $arr_info;
            }
            $result = array("total" => $total, "rows" => $array_list);
            return json($result);
        }elseif ($type==11){
            $OrderDepositSendModel = new OrderDepositSendModel();
            $list = $OrderDepositSendModel->where(['mw_id'=>$this->tombId,'customer_id'=>$this->customerId])->order('id desc')->limit($page,$limit)->select();
            $total =$OrderDepositSendModel->where(['mw_id'=>$this->tombId,'customer_id'=>$this->customerId])->count();
            $array_list=[];
            foreach ($list as $k => &$val) {
                $arr_info['add_time'] = date('Y-m-d H:i:s',$val['create_time']);
                $pay_info = OrderPayLogModel::where(['id'=>$val['pay_id']])->find();
                $od_info = OrderDepositModel::where(['id'=>$val['deposit_id']])->find();
                $ArchivesDeceased_info = ArchivesDeceasedModel::where(['deceased_id'=>$val['deceased_id']])->find();
                $arr_info['buyer_name'] = $val['buyer_name'];
                $arr_info['handle']['buyer_name'] = $val['buyer_name'];
                $arr_info['handle']['buyer_sex'] =   $val['buyer_sex']==1?"男":($val['buyer_sex']==2?"女":"");
                $arr_info['handle']['buyer_phone'] = $val['buyer_phone'];
                $arr_info['handle']['relationship'] = $val['relationship'];
                $arr_info['handle']['cart_type'] = cart_type('cart', $val['cart_type']);
                $arr_info['handle']['cart_num'] = $val['cart_num'];
                $arr_info['handle']['cart_address'] = $val['cart_address'];
                $arr_info['handle']['file_url'] = cmf_get_image_preview_url($val['file_cart']);
                $arr_info['handle']['handle_name'] =  $val['handle_name'];
                $arr_info['handle']['handle_time'] =  date('Y-m-d H:i:s',$val['create_time']);
                $arr_info['deceased_name'] = $ArchivesDeceased_info['deceased_name'];
                $arr_info['deceased']['deceased_name'] = $ArchivesDeceased_info['deceased_name'];
                $arr_info['deceased']['gender'] =  $ArchivesDeceased_info['gender']==1?"男":($ArchivesDeceased_info['gender']==2?"女":"");
                $arr_info['deceased']['date_birth'] = $ArchivesDeceased_info['date_birth'];
                $arr_info['deceased']['date_death'] = $ArchivesDeceased_info['date_death'];
                $arr_info['deceased']['relationship_users'] = !empty($ArchivesDeceased_info['relationship_users'])?empty($ArchivesDeceased_info['relationship_users']):'';

                $arr_info['convergence_type'] =  $ArchivesDeceased_info['convergence_type']==1?"骨灰":($ArchivesDeceased_info['convergence_type']==2?'骨殖':'');
                $arr_info['cremation_certificate_img'] = cmf_get_image_preview_url($ArchivesDeceased_info['cremation_certificate']);
                $arr_info['deposit_time'] = date('Y-m-d H:i:s',$od_info['deposit_time']);
                $arr_info['deposit_end_time'] = $od_info['deposit_end_time'];
                $arr_info['deposit_cost'] = $val['deposit_cost'].'/年';
                $arr_info['storage_time'] = $val['storage_time'];
                $arr_info['original_price'] =  -$val['original_price'];
                $arr_info['total_price'] = $val['total_price'];
                $arr_info['actual_amount'] = $val['actual_amount'];
                $arr_info['pay_name'] = cmf_get_admin_name($pay_info['pay_real_name']);
                $arr_info['extension_time'] = unixtime_to_date($val['extension_time'],'Y-m-d H:i:s');
                $arr_info['handle_name'] =   $val['handle_name'];
                $arr_info['remark'] = $val['remark'];

                $array_list[]= $arr_info;
            }
            $result = array("total" => $total, "rows" => $array_list);
            return json($result);
        }elseif ($type==12){
            $phone = $this->request->param('phone');
            $res = sendCodeSms($phone,$errorMsg);
            return json($res);
        }elseif ($type==13){
        }elseif ($type==15){
            //艺术墓 产品信息
            // 石材种类
            $this->getALlOption();

            $id = $this->request->param("id");
            $type = $this->request->param('type');
            $result = Db::name("product_mb")->where(['id' => $id])->find();


            $this->assign($result);
            // 详情  details-basics-cover-railing
            $infoData =  Db::name("product_mb_info")->where(['pro_id' => $id,'itype' => 1])->select();
            $this->assign('infoData', $infoData);
//            $part_arr['details'] = $infoData;
            // 基础
            $baseData =  Db::name("product_mb_info")->where(['pro_id' => $id,'itype' => 2])->select();
            $this->assign('baseData', $baseData);
//            $part_arr['basics'] = $baseData;
            // 盖板
            $plateData =  Db::name("product_mb_info")->where(['pro_id' => $id,'itype' => 3])->select();
            $this->assign('plateData', $plateData);
//            $part_arr['cover'] = $plateData;
            // 栏杆
            $railData =  Db::name("product_mb_info")->where(['pro_id' => $id,'itype' => 4])->select();
            $this->assign('railData', $railData);
//            $part_arr['railing'] = $railData;
            // 附件
            $annexData = Db::name("product_mb_annex")->where(['mb_id' => $id])->select();
            $this->assign('annexData', $annexData);
//            $part_arr['annex'] = $annexData;

//            $this->assign('partJson', json_encode($part_arr));
            $this->assign('type_mb', $type);
            return $this->fetch('rock_order/product_info');

        }
    }


    // 合同 地址
    public function ajax_contract($t=''){
        $modelContract = new ContractModel();
//        $modelContract->qianmu();

        if ($t=='jc_gs'){

        }elseif ($t=='az'){}

       $jc_gs =  'document/contract/qianmu.docx';
       $jc_gs =  'document/contract/寄存证-挂失.docx';
       $az_bg =  'document/contract/安葬证-变更.docx';
       $an_gs =  'document/contract/安葬证-挂失.docx';
    }

    protected function array_conventional(){
        $conventional=[
            ['id'=>1,'name'=>'描金描红','unit'=>'次','price'=>'50','gq'=>'3','zb'=>'1','type'=>'1','deliver_time'=>date('Y-m-d',strtotime("+3 day"))],
            ['id'=>2,'name'=>'勾缝打胶','unit'=>'次','price'=>'0','gq'=>'3','zb'=>'0','type'=>'1','deliver_time'=>date('Y-m-d',strtotime("+3 day"))],
            ['id'=>3,'name'=>'墓石矫正','unit'=>'次','price'=>'0','gq'=>'3','zb'=>'0','type'=>'1','deliver_time'=>date('Y-m-d',strtotime("+3 day"))],
            ['id'=>4,'name'=>'内穴防水','unit'=>'套','price'=>'500','gq'=>'7','zb'=>'1','type'=>'1','deliver_time'=>date('Y-m-d',strtotime("+7 day"))],
            ['id'=>5,'name'=>'基层防水','unit'=>'套','price'=>'300','gq'=>'3','zb'=>'1','type'=>'1','deliver_time'=>date('Y-m-d',strtotime("+3 day"))],
            ['id'=>6,'name'=>'绿化布置','unit'=>'株','price'=>'0','gq'=>'7','zb'=>'0','type'=>'1','deliver_time'=>date('Y-m-d',strtotime("+7 day"))],
            ['id'=>7,'name'=>'绿篱修整','unit'=>'次','price'=>'0','gq'=>'3','zb'=>'0','type'=>'1','deliver_time'=>date('Y-m-d',strtotime("+3 day"))],
            ['id'=>8,'name'=>'刻字修复','unit'=>'套','price'=>'1000','gq'=>'3','zb'=>'0','type'=>'1','deliver_time'=>date('Y-m-d',strtotime("+3 day"))],
            ['id'=>9,'name'=>'石材修补','unit'=>'套','price'=>'500','gq'=>'3','zb'=>'1','type'=>'1','deliver_time'=>date('Y-m-d',strtotime("+3 day"))],
            ['id'=>10,'name'=>'拜道维修','unit'=>'套','price'=>'1500','gq'=>'3','zb'=>'1','type'=>'1','deliver_time'=>date('Y-m-d',strtotime("+3 day"))],
        ];
        return $conventional;
    }

}

